import java.sql.{Connection, DriverManager, PreparedStatement}
import scala.collection.mutable
import scala.io.Source

object WordCountScala {
  def main(args: Array[String]): Unit = {
    val filePath = "src/main/resources/words.txt" // 文件路径
    val jdbcUrl = "jdbc:mysql://localhost:3306/word_count" // 数据库URL
    val username = "root" // 数据库用户名
    val password = "123456" // 数据库密码

    // 读取文件并统计单词出现次数
    val wordCountMap = readAndCountWords(filePath)

    // 找出出现次数最多的前五个单词
    val topWords = getTopNWords(wordCountMap, 5)

    // 将结果写入MySQL数据库
    writeTopWordsToDatabase(topWords, jdbcUrl, username, password)
  }

  // 读取文件并统计单词出现次数
  def readAndCountWords(filePath: String): Map[String, Int] = {
    val wordCountMap = mutable.Map[String, Int]().withDefaultValue(0)
    val source = Source.fromFile(filePath)
    try {
      for (line <- source.getLines()) {
        line.split("\\s+").foreach { word =>
          wordCountMap(word) += 1
        }
      }
    } finally {
      source.close()
    }
    wordCountMap.toMap
  }

  // 找出出现次数最多的前N个单词
  def getTopNWords(wordCountMap: Map[String, Int], n: Int): List[(String, Int)] = {
    wordCountMap.toList.sortBy(_._2)(Ordering[Int].reverse).take(n)
  }

  // 将结果写入MySQL数据库
  def writeTopWordsToDatabase(topWords: List[(String, Int)], jdbcUrl: String, username: String, password: String): Unit = {
    val connection: Connection = DriverManager.getConnection(jdbcUrl, username, password)
    val sql = "INSERT INTO top_words (word, count) VALUES (?, ?)"
    val preparedStatement: PreparedStatement = connection.prepareStatement(sql)
    try {
      for ((word, count) <- topWords) {
        preparedStatement.setString(1, word)
        preparedStatement.setInt(2, count)
        preparedStatement.executeUpdate()
      }
    } finally {
      preparedStatement.close()
      connection.close()
    }
  }


}
